package org.xm.sk.service.security;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.xm.sk.common.ToolsUtil;

public class UserPasswordEncoder implements PasswordEncoder {

    private static final Logger logger = LoggerFactory
            .getLogger(UserPasswordEncoder.class);

    @Autowired
    private MessageSource messages;

    @Override
    public String encode(CharSequence rawPassword) {
        try {
            return ToolsUtil.desdecrypt(rawPassword.toString());
        } catch (Exception e) {
            if (logger.isErrorEnabled()) {
                logger.error(e.getMessage(), e);
            } else {
                e.printStackTrace();
            }
        }
        return rawPassword.toString();
    }

    @Override
    public boolean matches(CharSequence rawPassword, String encodedPassword) {
        if (encodedPassword == null || encodedPassword.length() == 0) {
            logger.warn("Empty encoded password");
            return false;
        }
        boolean result = encode(rawPassword).equals(encodedPassword);
        if (!result)
            throw new BadCredentialsException(messages.getMessage(
                    "login.loginmsg.loginfail.invalid.password", null,
                    "The Password is invalid.", null));
        return result;
    }

}
